import { Button, Col, Empty, Row, Space } from 'antd'
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { filterProduct } from '../../store/actions/product.action'
import { AppState } from '../../store/reducers'
import { ProductState } from '../../store/reducers/product.reducer'
import Checkbox from './Checkbox'
import Layout from './Layout'
import ProductItem from './ProductItem'
import Radiobox from './Radiobox'

const Shop = () => {
  const dispatch = useDispatch()
  const {filter} = useSelector<AppState,ProductState>(state=>state.product)
  const [skip, setSkip] = useState<number>(0)
  const [myFilter, setMyFilter] = useState<{category: string[], price: number[]}>({category:[], price:[]})
  
  useEffect(()=>{
    setSkip(0)
  },[myFilter])
  
  useEffect(()=>{
    console.log(myFilter)
    dispatch(filterProduct({filters: myFilter,skip}))
  }, [myFilter,skip])

  const filterDom = () => (
    <Space size="middle" direction="vertical">
      <Checkbox handleFilter={(category:string[])=>{
        setMyFilter({...myFilter, category})
      }}  />
      <Radiobox  handleFilter={(price:number[])=>{
        setMyFilter({...myFilter, price})
      }}  />
    </Space>
  )

  const loadMore = () => {
    return <Row>
      {filter.result.size >=4 && <Button onClick={()=>{setSkip(skip+4)}}>加载更多</Button>}
    </Row>
  }

  const emptyWrapper = () => {
    return <Row>
    {filter.result.size === 0 && <Empty />}
    </Row>
  }

  const productDom = () => (
    <Row gutter={[16,16]}>
    {
      filter.result.data.map(item => (
        <Col key={item._id} span="6">
          <ProductItem product={item} />
        </Col>
      ))
    }
  </Row>
  )
  return (
    <Layout title="拉钩商城" subTitle="请挑选你喜欢的商品">
      <Row>
        <Col span="4">
          {filterDom()}
        </Col>
        <Col span="20">
          {productDom()}{loadMore()}{emptyWrapper()}
        </Col>
      </Row>
    </Layout>
  )
}
export default Shop